package com.rtech.app.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.rtech.app.exception.SearchException;
import com.rtech.app.service.TraversalService;
import com.rtech.app.model.Error;
import com.rtech.app.model.File;
import com.rtech.app.model.Node;

/**
 * Class exposing the requested service to end user.
 * 
 * @author ruchi.singhal
 * 
 */
@Controller
public class TraversalServiceController {

	protected static Logger logger = Logger
			.getLogger("TraversalServiceController");

	@Autowired
	TraversalService traversalService;

	/**
	 * URL for Directory Search.
	 * 
	 * @param fullPath
	 * @return
	 */
	@RequestMapping(value = { "dirSearch" }, method = RequestMethod.GET, produces = "application/xml")
	public @ResponseBody
	ResponseEntity<Node> directorySearch(@RequestParam("dirPath") String dirPath) {

		if (dirPath == null || (dirPath != null && dirPath.trim().equals(""))) {
			Error error = new Error("dir path cannot be empty or null");
			return new ResponseEntity<Node>(error, HttpStatus.BAD_REQUEST);
		}
		com.rtech.app.model.Directory response = null;

		response = traversalService.directorySearch(dirPath);
		logger.debug("Exiting from directorySearch() >>> ");
		return new ResponseEntity<Node>(response, HttpStatus.OK);

	}

	/**
	 * URL for File Serach.
	 * 
	 * @param filePath
	 * @return
	 */

	@RequestMapping(value = { "fileSearch" }, method = RequestMethod.GET, produces = "application/xml")
	@ResponseBody
	public ResponseEntity<Node> fileSearch(
			@RequestParam("filePath") String filePath) {

		if (filePath == null
				|| (filePath != null && filePath.trim().equals(""))) {
			Error error = new Error("file Path cannot be empty or null");
			return new ResponseEntity<Node>(error, HttpStatus.BAD_REQUEST);
		}

		File file = null;

		file = traversalService.fileSearch(filePath);
		logger.debug(file + "-- File information ");
		logger.debug("Exiting from fileSearch() >>> ");
		return new ResponseEntity<Node>(file, HttpStatus.OK);

	} // end of fileSearchMethod

	@ExceptionHandler
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ResponseBody
	public ResponseEntity<Node> handleControllerException(
			SearchException exception) {
		Error error = new Error("search error");
		return new ResponseEntity<Node>(error, HttpStatus.BAD_REQUEST);
	}

} // end of class